#include "queue.h"

int queue_getLength(Circular_Queue *Queue)
{
	return (Queue->max + Queue->tail - Queue->head) % Queue->max;
}
bool queue_isEmpty(Circular_Queue *Queue)
{
	return (Queue->tail == Queue->head);
}
bool queue_isFill(Circular_Queue *Queue)
{
	return ((Queue->tail + 1) % Queue->max == Queue->head);
}
int push_queue(Circular_Queue *Queue, uint8_t element)
{
	if (queue_isFill(Queue))
		return -1;
	Queue->buf[Queue->tail] = element;
	Queue->tail = (Queue->tail + 1) % Queue->max;
	return true;
}
int pop_queue(Circular_Queue *Queue)
{
	uint8_t tmp = 0;
	if (queue_isEmpty(Queue) == true)
		return -1;
	tmp = Queue->buf[Queue->head];
	Queue->head = (Queue->head + 1) % Queue->max;
	return tmp;
}
int queue_read(Circular_Queue *Queue, uint8_t *buf, int len)
{
	int i = 0, j = 0;
	if (queue_isEmpty(Queue) == true)
		return -1;
	j = queue_getLength(Queue);
	if (j < len)
		len = j;
	for (i = 0; i < len; i++)
	{
		buf[i] = pop_queue(Queue);
	}
	return len;
}
int queue_write(Circular_Queue *Queue, uint8_t *buf, int len)
{
	int i = 0;
	for (i = 0; i < len; i++)
	{
		if (push_queue(Queue, buf[i]) == -1)
			return i + 1;
	}
	return len;
}
